#include "stdafx.h"

#include "MainWndMemoMode.h"
#include "MainWndListMode.h"
#include "MemoFile.h"

#include "Utils.h"

/*
    CFontHandle font = AtlGetDefaultGuiFont();
    memoView.SetFont(font);

    VIEWATTRIBUTES  viewAttr;
    memset(&viewAttr, 0, sizeof(viewAttr));
    viewAttr.mask = VIEWATTRIBUTE_ZOOM;
    viewAttr.uZoom = 100;

    memoView.SetViewAttributes(&viewAttr);    */

void MainWndMemoMode::Init()
{
    if ( !memoView.IsWindow() ) {
        memoView.Create( host.m_hWnd, host.rcDefault, NULL, WS_VISIBLE | WS_VSCROLL | WS_CHILD );
    }

    host.m_hWndClient = memoView.m_hWnd;
    host.CreateSimpleCEMenuBar(IDR_EDIT_MENU, SHCMBF_HMENU);
    ::SHDoneButton(host.m_hWnd, SHDB_SHOW);

    memoView.SetModify(FALSE);

    if ( host.IsWindow() )
    {
        RecalcLayout();
        memoView.ShowWindow( SW_SHOW );
        memoView.SetFocus();
    }

    if (FileUtils::FileExists(memo->FileName))
        memoView.Load(memo->FileName, memo->Unicode);
}

MainWndMemoMode::MainWndMemoMode( MainWnd& window, std::auto_ptr<MemoFile> m )
    : host ( window )
    , memoView( host.memoView )
    , memo( m )
{          
    if ( memo.get() == NULL ) {
        std::wstring fileName = MemoFile::CreateName( host.options->WorkingDir() );
        memo = std::auto_ptr<MemoFile>( new MemoFile( fileName, host.options->NewInUnicode() ) );
    }

    Init();
}

void MainWndMemoMode::RecalcLayout()
{
    if ( !memoView.IsWindow() )
        return;

    CRect rect;
    host.GetClientRect(&rect);
    memoView.SetWindowPos(NULL, 0, 0, rect.Width(), rect.Height(), SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}

LRESULT MainWndMemoMode::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    RecalcLayout();
    return bHandled = FALSE;
}

LRESULT MainWndMemoMode::OnContextMenu(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
    PNMRGINFO pnmrgi = (PNMRGINFO)pnmh ;
    CMenuHandle menu;

    menu.LoadMenu(IDR_EDIT_MENU);
    menu = menu.GetSubMenu(0);

    return menu.TrackPopupMenu( TPM_HORIZONTAL | TPM_VERTICAL, pnmrgi->ptAction.x, pnmrgi->ptAction.y, host.m_hWnd);
}

LRESULT MainWndMemoMode::OnOk(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
    MainWndMode* newMode = NULL;

    try
    {
        host.CurrentMode = NULL;
        memoView.ShowWindow( SW_HIDE );
        ::SHDoneButton(host.m_hWnd, SHDB_HIDE);

        newMode = new MainWndListMode( host );
        host.CurrentMode = newMode;

        delete this;
    }

    // hell ugly -> improve
    catch (...)
    {
        host.CurrentMode = this;
        host.m_hWndClient = memoView.m_hWnd; 

        if ( newMode != NULL )
            delete newMode;
    }

    return 0L;
}